package com.youren.health.controller;


import com.aliyuncs.exceptions.ClientException;
import com.youren.health.constant.MessageConstant;
import com.youren.health.constant.RedisMessageConstant;
import com.youren.health.entity.Result;
import com.youren.health.utils.SMSUtils;
import com.youren.health.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;


/**
 * @program: health_parent
 * @author: You_ren_a
 * @create: 2020-11-30 10:06
 **/

@RestController
@RequestMapping("/validateCode")
public class ValidateCodeController {

    @Autowired
    private JedisPool jedisPool;


    @PostMapping("/send4Order")
    public Result send4Order(String telephone){
        Jedis jedis = jedisPool.getResource();
        String key = RedisMessageConstant.SENDTYPE_ORDER + "_" + telephone;
        String codeInRedis = jedis.get(key);
        if (codeInRedis==null) {
            Integer code = ValidateCodeUtils.generateValidateCode(6);
            try {
                // 发送验证码
                SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE, telephone, code + "");
                // 存入redis，有效时间为10分钟
                jedis.setex(key, 60*60, code + "");
                // 返回成功
                return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
            } catch (ClientException e) {
                e.printStackTrace();
                // 发送失败
                return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
            }
        }
        return new Result(true , MessageConstant.SEND_VALIDATECODE_SUCCESS);
    }




    @PostMapping("/send4Login")
    public Result send4Login(String telephone){
        Jedis jedis = jedisPool.getResource();
        String key = RedisMessageConstant.SENDTYPE_LOGIN + "_" + telephone;
        String codeInRedis = jedis.get(key);
        if (codeInRedis==null) {
            Integer code = ValidateCodeUtils.generateValidateCode(6);
            try {
                // 发送验证码
                SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE, telephone, code + "");
                // 存入redis，有效时间为10分钟
                jedis.setex(key, 60*60, code + "");
                // 返回成功
                return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
            } catch (ClientException e) {
                e.printStackTrace();
                // 发送失败
                return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
            }
        }
        return new Result(true , MessageConstant.SEND_VALIDATECODE_SUCCESS);
    }
}
